<?php

// 支付宝小程序sdk服务类
namespace App\Service;


use App\Utils\AES;
use Illuminate\Support\Facades\Log;

class ZFBService
{
    public $config = [
        'appId' => '2021005129639803',
        'privateKey' => 'MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQD1fAsCz3bEXLlZwsAs+Xj52riubgQiYPSds4ofDC6Wew1KYtI7+4wbIBqZ0Q+UHlQCUlZqDxpPGyTpOD+fYSMiULVurNCKsLjarxv7JKj/8ft6xWg5c5UAMpnRUiavqFrZEdJRgnVPwWigpVDg32mPTpxvZkBk8UbEgvDrDcL+DYWZrQjP6JLIHog1iUor+K5mNP7TvQr4WEZiwJwdP46p6a696MvvY2b83oy0PLzwp/Z58oUDpQgYiSkW1AsYkfu16Nrohjh61gzj8rPYCq0f5+xRlHHlTptXJlwl0Iid1WlCHbv5kvzDfw7KjpkvvWie0CD7BYXOzNwrrCct2llnAgMBAAECggEBAKOlyo1YEnu6uJE/A++3a09c4KrfioAElG2g553k+BW2+FgzYqU7/t2CXFlYBgOe6DAYBaV0ZfyAQu36Ymd0UQCqPxkFuYwLXV/jRkr42HSvMw9YFC/gfl8AXIwvMLz/BXkZqVRPHLdLXt1g93bBWNSA+kZFKv5f3eZYyBRaOzgyKyvTLVh8gTZltTzwshvBTFr4ZMnAMs4DA/D6oPzQlmAz8LyL71UHuWa6EunyOad/ljSUQLywnsq/qcp8Y0ASXVhJQ3TeyuLNwQ8/bS1L9nV/HyVVHsVfH5uNQ6sfkYZCB+ihtbT6Po4lVneFaqzkCNhEfeUFi1P3IguLV36/+OkCgYEA/qwCaU+xJgXok3dQskV/mnab4xi2Q983fQShgwalBj6QJakqz0YYhT6ddz8t1aO0bpUnWoJXWyuOJ5cMVzd4DUl9sKpFK7Cge4NjU0Or/rQ1aKy5r/veTGQpPXjyFiR8mR33bzpwu8QlMyyiWOdCgIXR2RuELPwh+UgLoUf7qxsCgYEA9sPEsP/kZWZJLXpNh4gjC+4d+GP28pw81jZBWnkTodDp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        'encryptKey' => '6xnyLJ4xIcP3e4Jm8kIHLA==',
        'gateway' => 'openapi.alipay.com'
    ];

    protected $app;

    public function __construct()
    {
        $app = new \AopClient();
        $app->appId = $this->config['appId'];
        $app->rsaPrivateKey = $this->config['privateKey'];
        $app->alipayrsaPublicKey = $this->config['alipayPublicKey'];
        $app->encryptKey = $this->config['encryptKey'];
        $app->signType= "RSA2";
        $this->app = $app;
    }

    public function getUserId($authCode)
    {
        $request = new \AlipaySystemOauthTokenRequest();
        $request->setCode($authCode);
        $request->setGrantType('authorization_code');

        $response = $this->app->execute($request);
        Log::info('MpService getUserId result', [$authCode, $response]);
        $result = $response->alipay_system_oauth_token_response ?? null;
        if($result) {
            return $result->user_id;
        }
        return null;
    }

    public function decrypt($str)
    {
        $secretKey = $this->config['encryptKey'];
        //AES, 128 模式加密数据 CBC
        $str = base64_decode($str);
        $secretKey = base64_decode($secretKey);
        //设置全0的IV
        $iv = str_repeat("\0", 16);
        $decrypt_str = openssl_decrypt($str, 'aes-128-cbc', $secretKey, OPENSSL_NO_PADDING, $iv);
        $decrypt_str = stripPKSC7Padding($decrypt_str);
        return $decrypt_str;
    }
}
